package cn.edu.zafu.bigdata.x.hjn;

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UDPServer {
    public static void main(String[] args) {
        DatagramSocket socket = null;

        try {
            // 创建UDP套接字，监听端口12345
            socket = new DatagramSocket(12345);
            System.out.println("UDP服务端已启动，等待客户端请求...");

            byte[] receiveData = new byte[1024];

            while (true) {
                // 创建DatagramPacket接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);  // 接收数据

                // 获取客户端的地址和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前时间并格式化
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String currentTime = sdf.format(new Date());

                // 将当前时间转换成字节数组
                byte[] sendData = currentTime.getBytes();

                // 创建DatagramPacket发送给客户端
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                socket.send(sendPacket);  // 发送时间
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}
